package netty.c1.echoPractice;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;

/**
 * @author ChenweiLin
 * @create 2022-02-14 12:24
 */
public class EchoClient {
    public static void main(String[] args) {
        new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                //建议使用 ctx.alloc() 创建 ByteBuf
                                ByteBuf buffer = ctx.alloc().buffer(10);

                                //首次建立连接，发送 hello 信息
                                buffer.writeBytes("hello".getBytes());
                                ctx.writeAndFlush(buffer);

                                //思考：需要释放 buffer 吗
                            }
                        });
                        pipeline.addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buffer = msg instanceof ByteBuf ? ((ByteBuf) msg) : null;
                                System.out.println(buffer.toString(Charset.defaultCharset()));

                                //思考：需要释放 buffer 吗
                            }
                        });
                    }
                }).connect("127.0.0.1",8080);

    }
}
